import hashlib
from urllib import parse

import urllib3

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

def get_pt_sign(app, params_dict):
    """
    sign签名
    :param params_dict:
    :return:
    """
    # step0：将非空参数按key进行ASCII字典升序排列, 再将排序后的参数(key=value)以&拼接起来
    key_lists = sorted([key for key in params_dict.keys() if params_dict.get(key) or params_dict.get(key) == 0])
    sign_raw = "&".join(list(map(lambda key: key + "=" + str(params_dict.get(key)), key_lists)))
    # step1:用&拼接上md5(app_secret + app_id)生成的小写字符串
    secret_key = hashlib.md5((app["app_secret"] + app["app_id"]).encode(encoding='UTF-8')).hexdigest()
    sign_raw = sign_raw + "&" + secret_key
    # step2:将签名原串 url编码
    sign_raw = parse.quote_plus(sign_raw, safe="*")
    # step3:再对整个字符串进行md5加密, 生成小写的签名字符串
    signature = hashlib.md5(sign_raw.encode(encoding='UTF-8')).hexdigest()
    return signature
